package com.avic.rong.activity.login;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.avic.rong.BaseActivity;
import com.avic.rong.R;
import com.avic.rong.api.SendCodeApi;
import com.avic.rong.api.login_register.FindPwdApi;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.RegexUtils;
import com.avic.rong.utils.SharedPreferencesUtil;
import com.avic.rong.utils.StatusBarUtil;
import com.avic.rong.utils.StringUtils;
import com.avic.rong.utils.TimeCount;
import com.avic.rong.utils.ToastTools;
import com.avic.rong.wedgit.StringUtil;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bingoogolapple.swipebacklayout.BGASwipeBackHelper;

//登录注册-找回密码
public class FindPwdActivity extends RxAppCompatActivity implements   BGASwipeBackHelper.Delegate{

    @BindView(R.id.img_return)
    ImageView img_return;
    @BindView(R.id.type_phone)
    EditText type_phone;
    @BindView(R.id.type_code)
    EditText type_code;
    @BindView(R.id.tv_send_code)
    TextView tv_send_code;
    @BindView(R.id.edittext_newpwd)
    EditText edittext_newpwd;
    @BindView(R.id.btn_commit_find)
    Button btn_commit_find;
    @BindView(R.id.tv_not_findyzma)
    TextView tv_not_findyzma;
    private FindPwdApi findPwdApi;
    private String phone;
    private String newPwd;
    private BGASwipeBackHelper mSwipeBackHelper;
    private InputMethodManager imm;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find_pwd);

        ButterKnife.bind(this);

        //设置状态栏颜色
        StatusBarUtil.setStatusBarColor(this,getResources().getColor(R.color.color_loginbg));
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

        edittext_newpwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length()>=6){
                    btn_commit_find.setBackgroundResource(R.mipmap.bg_btlogin);
                    btn_commit_find.setTextColor(getResources().getColor(R.color.white));
                    btn_commit_find.setEnabled(true);
                }else {
                    btn_commit_find.setBackgroundResource(R.mipmap.grey_login);
                    btn_commit_find.setTextColor(getResources().getColor(R.color.black_text));
                    btn_commit_find.setEnabled(false);
                }
            }
        });

        initSwipeBackFinish();
        overridePendingTransition(R.anim.slide_in_right, R.anim.keep);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // TODO Auto-generated method stub
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            if (this.getCurrentFocus() != null) {
                if (this.getCurrentFocus().getWindowToken() != null) {
                    imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
                }
            }
        }
        return super.onTouchEvent(event);
    }

    public static Intent queryIntent(Context context) {
        Intent intent = new Intent(context, FindPwdActivity.class);
        return intent;
    }

    @OnClick({R.id.img_return, R.id.tv_send_code, R.id.btn_commit_find, R.id.tv_not_findyzma})
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.img_return:
                finish();
                break;
            case R.id.tv_send_code:
                sendCode();
                break;
            case R.id.btn_commit_find:
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                findPwd();
                break;
            case R.id.tv_not_findyzma:
                startActivity(NotGetCodeActivity.queryIntent(this));
                break;
        }
    }

    private void findPwd() {
        phone = type_phone.getText().toString().trim();
        String code = type_code.getText().toString().trim();
        newPwd = edittext_newpwd.getText().toString().trim();
        String math = "^[0-9a-zA-Z]{6,32}$";
        if (StringUtil.isEmpty(phone)||StringUtil.isEmpty(code)){
            ToastTools.showPublicToast("手机号或验证码不能为空");
            if (StringUtil.isEmpty(newPwd)){
                ToastTools.showPublicToast("密码不能为空");
            }
            return;
        }
        boolean matches = newPwd.matches(math);

        if (!matches){
            ToastTools.showPublicToast("密码格式不正确");
            return;
        }
        findPwdApi = new FindPwdApi(FindPwdActivity.this,findPwdListener );
        findPwdApi.setArguments(phone,code, newPwd);
        findPwdApi.setCancel(false);
        findPwdApi.setShowProgress(true);
        HttpManager.getInstance().doHttpDeal(findPwdApi);

    }
    HttpOnNextListener<BaseResultEntity> findPwdListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            if (baseResultEntity.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)){//成功
                SharedPreferencesUtil.getInstance().put("username",phone);
                SharedPreferencesUtil.getInstance().put("password",newPwd);
               /* startActivity(LoginActivity.queryIntent(FindPwdActivity.this));*/
                finish();
            }else {
                Toast toast = Toast.makeText(FindPwdActivity.this, baseResultEntity.getMsg(), Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
            }
        }
    };

    private void sendCode() {
        String phone = type_phone.getText().toString().trim();
        if (StringUtils.isEmpty(phone)) {
            ToastTools.showPublicToast("手机号不能为空");
            return;
        }
        if (!RegexUtils.isMobileExact(phone)) {
            ToastTools.showPublicToast("手机号格式不正确");
            return;
        }
        SendCodeApi sendCodeApi = new SendCodeApi(this, sendCodeBeanListener);
        sendCodeApi.setArguments(phone,2,SharedPreferencesUtil.SIGN);
        sendCodeApi.setCancel(false);
        sendCodeApi.setShowProgress(true);
        HttpManager.getInstance().doHttpDeal(sendCodeApi);
    }

    HttpOnNextListener<BaseResultEntity> sendCodeBeanListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            if (baseResultEntity.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)){//成功
                timeOut();
            }else {
                Toast toast = Toast.makeText(FindPwdActivity.this, baseResultEntity.getMsg(), Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
            }
        }
    };

    private void timeOut() {
        TimeCount timeCount = new TimeCount(60000, 1000,tv_send_code,false);
        timeCount.start();
    }

    /**
     * 初始化滑动返回。在 super.onCreate(savedInstanceState) 之前调用该方法
     */
    private void initSwipeBackFinish() {
        mSwipeBackHelper = new BGASwipeBackHelper(this, this);

        // 「必须在 Application 的 onCreate 方法中执行 BGASwipeBackHelper.init 来初始化滑动返回」
        // 下面几项可以不配置，这里只是为了讲述接口用法。

        // 设置滑动返回是否可用。默认值为 true
        mSwipeBackHelper.setSwipeBackEnable(true);
        // 设置是否仅仅跟踪左侧边缘的滑动返回。默认值为 true
        mSwipeBackHelper.setIsOnlyTrackingLeftEdge(true);
        // 设置是否是微信滑动返回样式。默认值为 true
        mSwipeBackHelper.setIsWeChatStyle(true);
        // 设置阴影资源 id。默认值为 R.drawable.bga_sbl_shadow
        mSwipeBackHelper.setShadowResId(R.drawable.bga_sbl_shadow);
        // 设置是否显示滑动返回的阴影效果。默认值为 true
        mSwipeBackHelper.setIsNeedShowShadow(true);
        // 设置阴影区域的透明度是否根据滑动的距离渐变。默认值为 true
        mSwipeBackHelper.setIsShadowAlphaGradient(true);
        // 设置触发释放后自动滑动返回的阈值，默认值为 0.3f
        mSwipeBackHelper.setSwipeBackThreshold(0.3f);
        // 设置底部导航条是否悬浮在内容上，默认值为 false
        mSwipeBackHelper.setIsNavigationBarOverlap(false);
    }

    /**
     * 是否支持滑动返回。这里在父类中默认返回 true 来支持滑动返回，如果某个界面不想支持滑动返回则重写该方法返回 false 即可
     *
     * @return
     */
    @Override
    public boolean isSupportSwipeBack() {
        return false;
    }

    /**
     * 正在滑动返回
     *
     * @param slideOffset 从 0 到 1
     */
    @Override
    public void onSwipeBackLayoutSlide(float slideOffset) {
    }

    /**
     * 没达到滑动返回的阈值，取消滑动返回动作，回到默认状态
     */
    @Override
    public void onSwipeBackLayoutCancel() {
    }

    /**
     * 滑动返回执行完毕，销毁当前 Activity
     */
    @Override
    public void onSwipeBackLayoutExecuted() {
        mSwipeBackHelper.swipeBackward();
    }

    @Override
    public void onBackPressed() {
        // 正在滑动返回的时候取消返回按钮事件

        if (mSwipeBackHelper.isSliding()) {
            return;
        }
        mSwipeBackHelper.backward();
        overridePendingTransition(R.anim.keep, R.anim.out_from_right);
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.keep, R.anim.out_from_right);
    }

}
